import os
import re

from movie_spider.utils import parser
from movie_spider.utils.save_to_file import SaveFile


class Movie:

    def __init__(self, title, detail_link, spider=None):
        self.title = title
        self.detail_link = detail_link
        self._download_links = []
        self.spider = spider

    @property
    def download_links(self):
        self._extract_download_links()
        return self._download_links

    def __getitem__(self, value):
        
        if value == "title":
            return self.title
        elif value == "detail_link":
            return self.detail_link
        elif value == "download_links":
            return self.download_links

    def _extract_download_links(self):
        pattern = re.compile(r'ftp://.*')
        url = parser.join_path_to_hostname(self.spider.source['base_url'], self.detail_link)
        url = url.replace("s.ygdy8.com","www.ygdy8.com")
        response = self.spider.send_http(url, host='www.ygdy8.com')

        html = self.spider.get_decoded_html(response)


        dlinks = html.find_all(text=pattern, href=True)
        
        self._download_links = [link.text for link in dlinks]

    def __str__(self):
        return f"<{self.__class__.__name__}: {self.title}>"

    def __repr__(self):
        return f"<{self.__class__.__name__}: {self.title}>"

class MovieList(SaveFile):
    """
    该用来是用来存放搜索结果
    支持查看搜索结果数量
    支持导出到不同的文件格式

    :params movies: 一个电影对象的列表
    """

    def __init__(self, movies):
        self._movies = movies
        super(MovieList, self).__init__(movies)
    

    @property
    def count(self):
        return len(self._movies)

    def __getitem__(self, n):
        return self._movies[n]

    def __str__(self):
        return "\n".join([m.title for m in self._movies])

    def __repr__(self):
        return "\n".join([m.title for m in self._movies])
